//
//  BoxTabBarController.swift
//  Box
//
//  Created by mn on 2025/3/28.
//

import UIKit
import SnapKit
class BoxTabBarController: UITabBarController {

    let tabBarView = TabBarView()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getUserInfo()
    }
    func getUserInfo() {
        UserManager.shared.update {
            [weak self]  in
            self?.selectedIndex = 0
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(tabBarView)
        tabBarView.onTabSelected = {
            [weak self] index in
            self?.selectedIndex = index
        }
        tabBarView.shouldSelectTab = {
            [weak self] index in
            guard let self else { return  false}
            if index == 0 {
                return true
            } else if UserManager.shared.isLogin() {
                return true
            } else {
                UserManager.shared.pushToLogin(selectedViewController)
                return false
            }
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(userDidLogout), name: .userDidLogout, object: nil)
        
        tabBarView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(20)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-28)
            make.height.equalTo(56)
        }
        
    }
    
    @objc func userDidLogout() {
        selectedIndex = 0
        tabBarView.select(at: 0)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
